from collections import Counter
import matplotlib.pyplot as plt
import matplotlib.patches as patches


def get_scholarship_summary(students, year):
    programs = [s["PROGRAM ID"][:3] for s in students if int(s["PROGRAM ID"][-2:]) + 2000 == year]
    count = Counter(programs)
    return "\n".join(f"{v} x {k}" for k, v in count.items())


def generate_sponsorship_grid(students, year):
    plt.close('all')

    height = max(3, 0.5 * len(students) + 1)
    fig, ax = plt.subplots(figsize=(6, height))
    ax.set_xlim(0, 3.5)
    ax.set_ylim(-1, len(students))
    ax.set_xticks([0.25, 1.25, 2.25, 3.25])
    ax.set_xticklabels(["Term 1", "Term 2", "Term 3", "Term 4"])
    ax.set_yticks([])

    for i, s in enumerate(students):
        name = f"{s['FIRST NAME']} {s['LAST NAME']} ({s['STUDENT TYPE']})"
        ite = s["ITE NUMBER"]

        widths = [0.5, 1, 1, 1]
        x = 0
        for w in widths:
            rect = patches.Rectangle((x, i - 0.4), w, 0.8, linewidth=1, edgecolor='black', facecolor='white')
            ax.add_patch(rect)
            x += w

        color = None
        x_start = 0
        width = 0

        if s["STUDENT TYPE"].upper().startswith("INTERNSHIP"):
            color = "yellow"
            if ite == 1:
                x_start = 0.5
                width = 1.5
            elif ite == 2:
                x_start = 2
                width = 1.5
        else:
            if ite == 1:
                color = "gray";  x_start = 0;   width = 1.5
            elif ite == 2:
                color = "brown"; x_start = 0.5; width = 1.5
            elif ite == 3:
                color = "black"; x_start = 2;   width = 1.5

        if color and width:
            bar = patches.Rectangle((x_start, i - 0.4), width, 0.8, linewidth=1, edgecolor='black', facecolor=color)
            ax.add_patch(bar)

        ax.text(-0.2, i, name, va='center', ha='right')

    legend_patches = [
        patches.Patch(color='gray', label='Placement 1'),
        patches.Patch(color='brown', label='Placement 2'),
        patches.Patch(color='black', label='Placement 3'),
        patches.Patch(color='yellow', label='Internship')
    ]
    ax.legend(
        handles=legend_patches,
        loc='lower center',
        bbox_to_anchor=(0.5, -0.4),
        ncol=3,
        fontsize=8,
        frameon=False
    )

    plt.subplots_adjust(left=0.5, bottom=0.3, right=0.8)
    return fig